package com.wondertek.mist.utils;

import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

public class NetworkUtil {
	public NetworkUtil(){
	}

	public static boolean isNetworkAvailable(Context ctx)
	{
		ConnectivityManager cm = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null)
			return false;
		NetworkInfo netinfo[] = cm.getAllNetworkInfo();
		if (netinfo == null)
			return false;
		for (int i = 0; i < netinfo.length; i++)
			if (netinfo[i].isConnected())
				return true;

		return false;
	}
	
	public static boolean isOpenWifi(final Context ctx) {
		final WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
		return wifi.isWifiEnabled();
	}

	public static boolean is3gDataActive(final Context ctx) {
		final TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
		int state = tm.getDataState();
		switch (state) {
		case TelephonyManager.DATA_CONNECTING:
		case TelephonyManager.DATA_CONNECTED:
			return true;
		case TelephonyManager.DATA_DISCONNECTED:
			return false;
		}
		return false;
	}
	
	public static boolean ping(String ip) {		
		URL url = null;
		int code = 0;
		try {
			url = new URL(ip);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(3 * 1000);
			conn.connect();
			code = conn.getResponseCode();			
		} catch (Exception e1) {			
			return false;
		}
		return code != 0;
	}	
	
}
